﻿
//==============================================================================
// 文件     ：StringExt.cs
// 功能概要 ：string扩展方法
//           
//           
// 作者    ：周薇
// 时间    ：2011年5月16日
// Copyright (c) 2011 重庆安运科技公司. All rights reserved.
//==============================================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Data;
using System.Diagnostics;

namespace Webcar.Utils
{
    public static class StringExt
    {
        ///<summary> 
        ///将指定字符串按指定长度进行剪切， 
        ///</summary> 
        ///<param name= "oldStr "> 需要截断的字符串 </param> 
        ///<param name= "maxLength "> 字符串的最大长度 </param> 
        ///<param name= "endWith "> 超过长度的后缀 </param> 
        ///<returns>如果超过长度，返回截断后的新字符串加上后缀，否则，返回原字符串 </returns> 
        public static string Truncat(this string oldStr, int maxLength, string endWith)
        {
            if (string.IsNullOrEmpty(oldStr))
                //   throw   new   NullReferenceException( "原字符串不能为空 "); 
                return oldStr + endWith;
            if (maxLength < 1)
                throw new Exception("返回的字符串长度必须大于[0] ");
            if (oldStr.Length > maxLength)
            {
                string strTmp = oldStr.Substring(0, maxLength);
                if (string.IsNullOrEmpty(endWith))
                    return strTmp;
                else
                    return strTmp + endWith;
            }
            return oldStr;
        }
        /// <summary>
        /// 将指定字符串按指定长度进行剪切
        /// </summary>
        /// <param name="oldStr"></param>
        /// <param name="maxLength"></param>
        /// <returns></returns>
        public static string Truncat(this string oldStr, int maxLength)
        {
            return oldStr.Truncat(maxLength, "...");
        }
        /// <summary>
        /// 安全的tostring 如果对象为null，返回string.empty
        /// </summary>
        /// <param name="ob"></param>
        /// <returns></returns>
        public static string ToSafeString(this object ob)
        {
            if (ob == null) return string.Empty;
            return ob.ToString();
        }
        /// <summary>
        /// Console.WriteLine封装
        /// </summary>
        /// <param name="str"></param>
        public static void WriteLine(this string str)
        {
            Console.WriteLine(str);
            
        }
        /// <summary>
        /// Debug.WriteLine封装
        /// </summary>
        /// <param name="str"></param>
        public static void DebugPrint(this string str)
        {
#if DEBUG
            Console.WriteLine(str);
#endif
        }
        /// <summary>
        /// PadRight的汉字双字节版本
        /// </summary>
        /// <returns></returns>
        public static string PadRightEx(this string data,int totalWidth, char padding)
        {
            string str = data.IsNull("");
            int len = str.GetByteLength();
            if (len >= totalWidth) return data;

            int pad_len = len - str.Length;

            return str.PadRight(totalWidth - pad_len, padding);
        }
        /// <summary>
        /// PadRight的汉字双字节版本
        /// </summary>
        /// <returns></returns>
        public static string PadRightEx(this string data, int totalWidth)
        {
            return data.PadRightEx(totalWidth, ' ');
        }

        /// <summary>
        /// DES加密方法
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string DESEncrypt(this string data)
        {
            
            return SecurityHelper.DESEncrypt(data, SecurityHelper.EncyptKey);
        }
        /// <summary>
        /// DES解密方法
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string DESDecrypt(this string data)
        {
            return SecurityHelper.DESDecrypt(data, SecurityHelper.EncyptKey);
        }
        /// <summary>
        /// 取得字符串的MD5
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string MD5Hash(this string str)
        {
            MD5 md5Hasher = MD5.Create();
            byte[] data = md5Hasher.ComputeHash(Encoding.GetEncoding("gb2312").GetBytes(str));

            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("X2"));
            }
            return sBuilder.ToString();

        }

        /// <summary>
        /// 取得对象hash
        /// </summary>
        /// <param name="ob"></param>
        /// <returns></returns>
        public static string Base64Hash(this object ob)
        {
            return SecurityHelper.HashObject(ob);
        }
        /// <summary>
        /// base64字符串转换为byte[]
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static byte[] FromBase64String(this string str)
        {
            return Convert.FromBase64String(str);
        }
        /// <summary>
        /// 是否一个值在一个IEnumerable中
        /// </summary>
        /// <param name="o"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static bool In(this object o, IEnumerable b)
        {
            foreach (object obj in b)
            {
                if (obj == o)
                    return true;
            }
            return false;
        }

        /// <summary>
        /// 字符串转换为DateTime?
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static DateTime? ToNullDateTime(this string value)
        {
            if (value.IsNull()) return null;
            return value.ToDateTime();
        }
        /// <summary>
        /// 字符串转换为DateTime
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static DateTime ToDateTime(this string value)
        {
            if (value.IsNull())
                return new DateTime();
            return DateTime.Parse(value);
        }

    
        /// <summary>
        /// 字符串转换为DateTime，如果格式不正确，返回default_value
        /// </summary>
        /// <returns></returns>
        public static DateTime TryToDateTime(this string value, string format,DateTime default_value)
        {
            DateTime ret = new DateTime();
            if(DateTime.TryParseExact(value, format, null, System.Globalization.DateTimeStyles.None,out ret))
            {
                return ret;
            }
            else
                return default_value;
        }
        /// <summary>
        /// 字符串按照指定的格式转换为DateTime
        /// </summary>
        /// <returns></returns>
        public static DateTime ToDateTime(this string value,string format)
        {
            return DateTime.ParseExact(value,format,null);
        }
        /// <summary>
        /// 字符串转换为decimal
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static Decimal ToDecimal(this string value)
        {
            if (string.IsNullOrEmpty(value)) return 0;
            return Decimal.Parse(value);
        }
        /// <summary>
        /// 字符串转换为bool
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool ToBool(this string value)
        {
            return bool.Parse(value);
        }
        /// <summary>
        /// 字符串转换为bool
        /// </summary>
        /// <param name="value"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static bool ToBool(this string value, bool defaultValue)
        {
            bool r;
            if (bool.TryParse(value, out r))
            {
                return r;
            }
            return defaultValue;
        }
        /// <summary>
        /// 切割字符串并且用省略号代替未显示部分
        /// </summary>
        /// <param name="s"></param>
        /// <param name="lenght"></param>
        /// <returns></returns>
        public static string AddEllipsisPoints(this string s, int lenght)
        {
            if (s.IsNull()) return string.Empty;

            if (s.Length < lenght)
            {
                return s;
            }

            return s.Substring(0, lenght) + "......";
        }

        /// <summary>
        /// 字符串转换为byte[]
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static byte[] ToDefaultBytes(this string value)
        {
            return Encoding.GetEncoding("gb2312").GetBytes(value);
        }
        /// <summary>
        /// 字符串转换为int
        /// </summary>
        /// <returns></returns>
        public static int ToInt(this string value)
        {
            return int.Parse(value.IsNull("0"));
        }
        /// <summary>
        /// 字符串转换为double
        /// </summary>
        /// <returns></returns>
        public static double ToDouble(this string value)
        {
            if (value == "")
                value = "0";
            return double.Parse(value);
        }
        /// <summary>
        /// 字符串转换为short
        /// </summary>
        /// <returns></returns>
        public static short ToShort(this string value)
        {
            if (value == "")
                value = "0";
            return short.Parse(value);
        }
        
        /// <summary>
        /// 字符串转换为float
        /// </summary>
        /// <returns></returns>
        public static float ToFloat(this string value)
        {
            if (value.IsNull())
                value = "0";
            return float.Parse(value);
        }
        /// <summary>
        /// 字符串转换为int
        /// </summary>
        /// <returns></returns>
        public static int ToInt(this string value, int defaultValue)
        {
            int r;
            if (int.TryParse(value, out r))
            {
                return r;
            }
            
            return defaultValue;
        }
        
        //public static string AsHexString().ToBytes()
        //{
        //    byte b;
        //}
        /// <summary>
        /// 整数转换为16进制
        /// </summary>
        /// <returns></returns>
        public static string ToHexNumber32(this int value)
        {
            return Convert.ToString(value, 16).ToUpper();
        }
        ///// <summary>
        ///// 整数转换为16进制
        ///// </summary>
        ///// <returns></returns>
        //public static string ToHexNumber64(this long value)
        //{
        //    return Convert.ToString(value, 16).ToUpper();
        //}
        /// <summary>
        /// 16进制字符串转换为整数
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        //public static int FromHexNumber32(this string value)
        //{
        //    return Convert.ToInt32(value, 16);
        //}
        
        /// <summary>
        /// 16进制字符串转换为整数
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        //public static long FromHexNumber64(this string value)
        //{
        //    return Convert.ToInt64(value, 16);  
        //}
        /// <summary>
        /// 忽略大小写比较字符串
        /// </summary>
        /// <param name="s"></param>
        /// <param name="s2"></param>
        /// <returns></returns>
        public static bool EqualsIgnoreCase(this string s, string s2)
        {
            return s.IsNull("").Equals(s2.IsNull(""), StringComparison.CurrentCultureIgnoreCase);
        }

        /// <summary>
        /// isnull
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool IsNull(this string s)
        {
            //扩展方法不会NullReferenceException
            return string.IsNullOrEmpty(s);
        }
        /// <summary>
        /// IsNull
        /// </summary>
        /// <param name="s"></param>
        /// <param name="s2"></param>
        /// <returns></returns>
        public static string IsNull(this string s,string s2)
        {
            //扩展方法不会NullReferenceException
            if (string.IsNullOrEmpty(s))
                return s2;
            return s;

        }
        /// <summary>
        /// IsNotNull
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool IsNotNull(this string s)
        {
            return !string.IsNullOrEmpty(s);

        }
        /// <summary>
        /// Trim后Upper
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string TrimAndUpper(this string s)
        {
            if (s.IsNull()) return s;
            return s.Trim().ToUpper();
        }

        /// <summary>
        /// 同Oracle的nvl
        /// </summary>
        /// <param name="s"></param>
        /// <param name="nullvalue"></param>
        public static string nvl(this string s,string nullvalue)
        {
            if(s.IsNull())
                return nullvalue;
            else
                return s;
        }
        /// <summary>
        /// 是否字符串是日期
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool IsDate(this string s)
        {
            DateTime dt = new DateTime();
            //DateTime dt=DateTime.Now;
            return DateTime.TryParseExact(s, "yyyy-MM-dd", null, System.Globalization.DateTimeStyles.None, out dt);
            //{
                //return ret;
            //return DateTime.TryParse(s, "",out dt);
        }
        /// <summary>
        /// 是否字符串是月份
        /// </summary>
        /// <param name="month"></param>
        /// <returns></returns>
        public static bool IsMonth(this string month)
        {
            string m = month + "-01";
            return m.IsDate();
        }
        public static int GetByteLength(this string s)
        {
            if (s.IsNull()) return 0;
            return Encoding.GetEncoding("gb2312").GetByteCount(s);
        }
        /// <summary>
        /// 得到string在指定编码下的byte[]长度
        /// </summary>
        /// <param name="s"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static int GetByteLength(this string s,Encoding encoding)
        {
            return encoding.GetByteCount(s);
        }

        /// <summary>
        /// 是否一个字符串是数字
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool IsNumber(this string s)
        {
            if (s.IsNull()) return false;
            long result = 0;
            return (long.TryParse(s, out result));
        }
        /// <summary>
        /// 是否一个字符串是数字
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool IsDecimal(this string s)
        {
            if (s.IsNull()) return false;
            decimal result = 0;
            return (decimal.TryParse(s, out result));
        }
        /// <summary>
        /// 按照byte截取字符串，英文长度1位，汉字长度2位
        /// </summary>
        /// <param name="s"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static String SubstringByte(this string s, int start,int length)
        {
            byte[] bytes = System.Text.Encoding.GetEncoding("gb2312").GetBytes(s);
            return System.Text.Encoding.GetEncoding("gb2312").GetString(bytes, start, length);
        }
        /// <summary>
        /// 按照byte截取字符串，英文长度1位，汉字长度2位
        /// </summary>
        /// <param name="s"></param>
        /// <param name="start"></param>
        /// <returns></returns>
        public static string SubstringByte(this string s, int start)
        {
            byte[] bytes = System.Text.Encoding.GetEncoding("gb2312").GetBytes(s);
            return System.Text.Encoding.GetEncoding("gb2312").GetString(bytes, start, bytes.Length - start);
        }
        /// <summary>
        /// 格式化字符串
        /// </summary>
        /// <returns></returns>
        public static string FormatWith(this string format, params object[] args)
        {
            return string.Format(format, args);
        }

        /// <summary>
        /// 删除第一次匹配的字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="removeString"></param>
        /// <returns></returns>
        public static string RemoveFirstMatchString(this string str, string removeString)
        {
            if (str.IndexOf(removeString) > -1)
            {
                return str.Remove(str.IndexOf(removeString), removeString.Length);
            }
            return str;
        }

        #region 正则表达式扩展

        public static bool IsMatch(this string s, string pattern)
        {
            if (s == null) 
                return false;
            else 
                return Regex.IsMatch(s, pattern); 
        }

        public static string Match(this string s, string pattern)
        {
            if (s == null) return "";
            return Regex.Match(s, pattern).Value;
        }
        #endregion

        /// <summary>
        /// 去除两端和中间的多个空格符--by YMS
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <returns>返回去除多个空格后的字符串</returns>
        public static string TrimAllSpace(this string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                var newStr = str.Trim().Split(' '); //全部拆解
                var sb = new StringBuilder();
                foreach (string item in newStr)
                {
                    if (!string.IsNullOrEmpty(item.Trim()))
                    {
                        sb.Append(item); //把为空的字符串组合起来
                    }
                }
                return sb.ToString();
            }
            return string.Empty;
        }

        public static string ExecuteDos(this string cmd)
        {
            Process process = new Process();
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.CreateNoWindow = true;
            process.Start();
            process.StandardInput.WriteLine(cmd);
            process.StandardInput.WriteLine("exit");
            return process.StandardOutput.ReadToEnd();
        }

    }

    #region SQL Extention
    
    public class SqlString
    {
        private string s;
        public SqlString(string s) { this.s = s; }
        public string Value 
        { 
            get
            { 
                return s;
            } 
        }
    }
    //public static class SqlStringExtension
    //{
    //    public static SqlString AsSqlString(this string s) { return new SqlString(s); }

    //    public static DataTable ExecuteDataTable(this SqlString cs)
    //    {
    //        return DBHelper.ExecuteDataTable(cs.Value);
    //    }
    //    public static int ExecuteNonQuery(this SqlString cs)
    //    {
    //        return DBHelper.ExecuteNonQuery(cs.Value);
    //    }
    //    public static string ExecuteScalar(this SqlString cs)
    //    {
    //        return DBHelper.ExecuteScalar(cs.Value);
    //    }
    //}
    #endregion

    #region Hex Extention
    public class HexString
    {
        private string s;
        public HexString(string s) { this.s = s; }
        public string Value
        {
            get
            {
                return s;
            }
        }
    }
    public static class HexStringExtension
    {
        public static HexString AsHexString(this string s) { return new HexString(s); }
        public static byte ToByte(this HexString value)
        {
            return byte.Parse(value.Value, System.Globalization.NumberStyles.HexNumber);
        }
        public static byte[] ToBytes(this HexString value)
        {
            return ByteHelper.HexString2Byte(value.Value);
        }
        public static byte[] ToBcdBytes(this HexString value)
        {
            return ByteHelper.BCDString2Bytes(value.Value);
        }

        public static int ToInt32(this HexString value)
        {
            return Convert.ToInt32(value.Value, 16);
        }
        public static long ToInt64(this HexString value)
        {
            return Convert.ToInt64(value.Value, 16);
        }

        ///// <summary>
        ///// 每隔2位转换为16进制数字
        ///// 例如0230900005 输出结果为 02 1E 5A 00 05
        ///// 
        ///// </summary>
        ///// <param name="value"></param>
        ///// <returns></returns>
        //public static string ToHex(this HexString hex)
        //{
        //    string value = hex.Value;
        //    if (!value.IsNumber()) return null;
        //    if ((value.Length % 2) != 0)
        //        value = "0" + value;
        //    StringBuilder sb = new StringBuilder();
        //    for (int i = 0; i < value.Length; i = i + 2)
        //    {
        //        string s = value.Substring(i, 2);
        //        sb.Append(byte.Parse(s).ToString("X2"));
        //    }
        //    return sb.ToString();
        //}
        ///// <summary>
        ///// ToHex的逆向函数
        ///// </summary>
        ///// <param name="value"></param>
        ///// <returns></returns>
        //public static string FromHex(this HexString hex)
        //{
        //    string value = hex.Value;
        //    if ((value.Length % 2) != 0)
        //        value = "0" + value;
        //    StringBuilder sb = new StringBuilder();
        //    for (int i = 0; i < value.Length; i = i + 2)
        //    {
        //        string aa = value.Substring(i, 2);
        //        string s = Convert.ToUInt16(aa, 16).ToString();
        //        if (s.Length > 2)
        //            throw new ApplicationException("FromHex函数溢出，参数为" + value);
        //        sb.Append(s.PadLeft(2, '0'));
        //    }
        //    return sb.ToString().ToUpper();
        //}

    }
    #endregion
 
    #region 正则表达式扩展
     public class RegexString
    {
        private string s;
        public RegexString(string s) { this.s = s; }
        public string Value
        {
            get
            {
                return s;
            }
        }
    }
     public static class RegexStringExtension
     {
         public static RegexString AsRegexString(this string s) { return new RegexString(s); }
         public static bool IsMatch(this RegexString s, string pattern)
         {
             if (s == null)
                 return false;
             else
                 return Regex.IsMatch(s.Value, pattern);
         }

         public static string Match(this RegexString s, string pattern)
         {
             if (s == null) return "";
             return Regex.Match(s.Value, pattern).Value;
         }
     }
        #endregion
}
